<template>
  <li :class="['menu-submenu',{'open': opened},{'active': active}]">
    <template v-if="!spread">
      <div class="submenu-title" @click="handlerClick">
        <slot name="title"></slot>
        <Icon type="ios-arrow-down" class="title-icon"></Icon>
      </div>
      <collapseTransition>
        <ul v-show="opened" ref="sub" class="submenu-box">
            <slot></slot>
        </ul>
      </collapseTransition>
    </template>
    <template v-if="spread">
         <layer v-model="opened" placeX="end" placeY="end" :space="0" :offsetY="-32">
             <div class="submenu-title" @click="handlerClick" slot="button">
              <slot name="title"></slot>
            </div>
            <ul  ref="sub" slot="body" class="submenu-box">
                <div class="submenu-name">{{title}}</div>
                    <slot></slot>
            </ul>
         </layer>
    </template>
  </li>
</template>
<script>
import Emitter from '../mixins/emitter';
import layer from '@/element/layer'
import collapseTransition from '@/element/collapseTransition';
export default {
  name: 'submenu',
  components: {
    layer,
    collapseTransition
  },
  props: {
     name: [String, Number],
     spread: Boolean,
     title: String
  },
  mixins: [ Emitter ],
  data () {
    return {
     opened: false,
     active: false
    //  spread: false
    }
  },
  watch: {
    spread() {
      this.opened = false;
    }
  },
  methods: {
    handlerClick() {
      this.updateState()
    },
    updateState() {
      this.opened = !this.opened;
      this.$nextTick(() => {
        this.dispatch('Menu', 'on-submenu-select', this.name);
      })
    }
  },
  mounted() {
    this.$on('on-update-active-submenu', name => {
      if (this.name !== name) this.opened = false;
    })
    this.$on('on-active-change', el => {
       if (!this.spread && this.$refs.sub === el.parentNode) {
          this.opened = true;  
       }
      //  if (this.$refs.sub === el.parentNode) {
      //     this.active = true;
      //  } else {
      //     this.active = false;
      //  }
    })
    this.$on('on-open-submenu', name => {
       if (this.name === name) {
          this.active = true;
       } else {
          this.active = false;
       } 
    })
    this.$on('on-update-spread', spread => {
       this.opened = false
       this.spread = spread;
       this.$nextTick(() => {
          this.dispatch('Menu', 'on-init-active-name');
       })
    })
  }
}
</script>
